package main

import (
	"database/sql"
	"fmt"
	"go.uber.org/zap"
	"google.golang.org/protobuf/proto"
	"laxkits/lib/laxmysql"
	"laxkits/lib/laxoffice"
	"laxkits/lib/laxutils"
	KKSG "laxkits/lib/ropb"
	"sync"
)


func queryInternal(wg *sync.WaitGroup, conn *laxmysql.LaxMySQLConn, roleIdx int, csvWriter *laxoffice.LaxCSVWriter) {
	defer wg.Done()
	zap.S().Infof("conn:%s, 开始查询role%d", conn.GetId(), roleIdx)
	var err error
	var role RoleItemReadNode
	role.Init()
	qsql := fmt.Sprintf("select serverid, id,name,account, ItemDataList_0, ItemDataList_1,ItemDataList_2,ItemDataList_3,ItemDataList_4 from player%d.role", roleIdx)
	if err = conn.LaxQuery(qsql, func(row *sql.Rows) error {
		if err = row.Scan(role.rowFields...); err != nil {
			zap.S().Warn("查询失败,", err)
			return err
		}
		role.Parse()
		itemCountMap := map[uint32]int64{}
		var itemAllCount int64 = 0
		for j := 0; j < 5; j++ {
			var pb KKSG.ItemDataList_0
			if err = proto.Unmarshal(role.GetItemData(j), &pb); err != nil {
				zap.S().Warn("序列化成pb失败:", err)
				return err
			}
			if pb.ItemDataList == nil || pb.ItemDataList.ItemDataList == nil {
				continue
			}
			for _, item := range pb.ItemDataList.ItemDataList {
				if _, ok := laxutils.ROGlobalConfigNode.ItemIdMap[item.ItemId]; ok {
					itemCountMap[item.ItemId] += item.ItemCount
					itemAllCount += item.ItemCount
					zap.S().Infof("%s mysqlid:%s 查找到道具:%d uid:%d 数量:%d 绑定:%d, player:%d, itemidx:%d", role.String(),
						conn.GetId(),
						item.ItemId,
						item.Uid,
						item.ItemCount,
						item.StateSign,
						roleIdx, j)
					if laxutils.ROGlobalConfigNode.ItemQueryCsvType == 0 {
						csvWriter.WriteOneLine([]string{
							laxutils.ToString(role.ServerId),
							laxutils.ToString(role.Id),
							role.Name, role.Account,
							laxutils.ToString(item.ItemId),
							laxutils.ToString(item.Uid),
							laxutils.ToString(item.ItemCount)})
					}
				}
			}
		}
		if laxutils.ROGlobalConfigNode.ItemQueryCsvType == 1 {
			for k, v := range itemCountMap {
				csvWriter.WriteOneLine([]string{
					laxutils.ToString(role.ServerId),
					laxutils.ToString(role.Id),
					role.Name, role.Account,
					laxutils.ToString(k), "0",
					laxutils.ToString(v)})
			}
		} else if laxutils.ROGlobalConfigNode.ItemQueryCsvType == 2 {
			csvWriter.WriteOneLine([]string{
				laxutils.ToString(role.ServerId),
				laxutils.ToString(role.Id),
				role.Name, role.Account, "0", "0",
				laxutils.ToString(itemAllCount)})
		}
		return nil
	}); err != nil {
		zap.S().Infof("执行出错: connid:%s, playeridx:%d, err:%s", conn.GetId(), roleIdx, err)
		return
	}
}

func TryQuery(conn *laxmysql.LaxMySQLConn, csvWriter *laxoffice.LaxCSVWriter) {
	if conn == nil || csvWriter == nil {
		return
	}
	var wg sync.WaitGroup
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go queryInternal(&wg, conn, i, csvWriter)
	}
	wg.Wait()
}
